<template>
  <div class="publish-container">
    <el-card>
      <template #header>
        <h2>发布资源</h2>
      </template>

      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input 
            v-model.trim="form.name"
            placeholder="请输入资源名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="资源分类" prop="categoryId">
          <el-select 
            v-model="form.categoryId"
            placeholder="请选择资源分类"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="资源位置" prop="location">
          <el-input 
            v-model.trim="form.location"
            placeholder="请输入资源位置"
          />
        </el-form-item>

        <el-form-item label="资源描述" prop="description">
          <el-input 
            v-model.trim="form.description"
            type="textarea"
            rows="4"
            placeholder="请输入资源描述"
          />
        </el-form-item>

        <el-form-item label="资源图片">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleFileChange"
            accept="image/*"
            multiple
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :loading="publishing"
          >
            发布资源
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useResourceStore } from '../stores/resource'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, UploadFile } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const resourceStore = useResourceStore()
const formRef = ref<FormInstance>()
const publishing = ref(false)

const categories = ref([
  { id: 1, name: '书籍' },
  { id: 2, name: '电子设备' },
  { id: 3, name: '体育用品' },
  { id: 4, name: '生活用品' },
  { id: 5, name: '其他' }
])

const form = ref({
  name: '',
  categoryId: '',
  location: '',
  description: ''
})

const fileList = ref<UploadFile[]>([])

const rules = {
  name: [
    { required: true, message: '请输入资源名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择资源分类', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入资源位置', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入资源描述', trigger: 'blur' }
  ]
}

const handleFileChange = (file: UploadFile) => {
  if (!file.raw) return
  const isImage = file.raw.type.startsWith('image/')
  const isLt10M = file.raw.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    fileList.value = fileList.value.filter(f => f.uid !== file.uid)
    return
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    fileList.value = fileList.value.filter(f => f.uid !== file.uid)
    return
  }
}

const handleFileRemove = (file: UploadFile) => {
  fileList.value = fileList.value.filter(f => f.uid !== file.uid)
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (!form.value.name?.trim()) {
        ElMessage.error('资源名称不能为空')
        return
      }

      if (fileList.value.length === 0) {
        ElMessage.error('请上传至少一张图片')
        return
      }

      publishing.value = true
      try {
        const dto = {
          ...form.value,
          categoryId: Number(form.value.categoryId)
        }
        
        const files = fileList.value.map(file => file.raw).filter((f): f is File => f !== undefined)
        const success = await resourceStore.publishResource(dto, files)
        if (success) {
          ElMessage.success('发布成功')
          router.push('/home/resources')
        }
      } catch (error: any) {
        const errorMsg = error.response?.data?.msg || '发布失败，请重试'
        ElMessage.error(errorMsg)
        console.error('发布失败:', error.response?.data || error)
      }
    } else {
      ElMessage.error('请填写完整的表单信息')
      return
    }
  })
}

const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  fileList.value = []
}
</script>

<style scoped>
.publish-container {
  padding: 20px;
}

.el-card :deep(.el-card__header) {
  padding: 15px 20px;
}

.el-card :deep(.el-card__header) h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.el-form {
  max-width: 800px;
  margin: 0 auto;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 